import React, { useEffect, useState, useRef } from 'react'
import { useModel, history, useSearchParams } from '@umijs/max'
import { Form, Tabs, Space, Button, Switch, Input, Radio, Card } from 'antd'
import SkuTable from './SkuTable.jsx'
import styles from './index.less'
import { Checkbox } from 'antd'

let timer = null
const skuNameList = ['first_sku_value', 'second_sku_value', 'third_sku_value']
const sourceMap = ['package_name', 'first_sku_value', 'second_sku_value', 'third_sku_value']

const SkuTableWrapper = props => {
  const { value, onChange } = props
  const { Spu, Package, Disabled, FormRef } = useModel('Goods')
  const [tableColumn, setTableColumn] = useState([])
  const [prefixColumn, setPrefixColumn] = useState([])
  const [suffixColumn, setSuffixColumn] = useState([])
  const [rentPeriodColumn, setRentPeriodColumn] = useState([])
  const [skuList, setSkuList] = useState([])
  const [showPer, setShowPer] = useState(false)
  const skuListRef = useRef([])
  const periodListRef = useRef([])
  const dataStore = useRef([])

  const originColumns = [
    {
      title: '是否展示',
      dataIndex: 'show_flag',
      render: (_, record, index) => (
        <Switch defaultChecked={Boolean(_)} disabled={Disabled} onChange={e => handleChangeIsHide(e, index)}></Switch>
      )
    },
    {
      title: '库存',
      dataIndex: 'store',
      editable: true,
      notPrice: true,
      type: 'number'
      // inputWidth: 40
    },
    {
      title: '官方指导价',
      dataIndex: 'selling_price',
      editable: true,
      type: 'number'
    },
    // {
    //   title: '押金/首付款',
    //   dataIndex: 'deposit',
    //   editable: true,
    //   type: 'number'
    // },
    {
      title: '买断总价/购买价',
      dataIndex: 'buyout_price',
      editable: true,
      type: 'number'
    }
  ]
  useEffect(() => {
    reformat()
  }, [Spu, Package])

  const reformat = () => {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      formatSkuList()
    }, 300)
  }

  useEffect(() => {
    setTableColumn([...prefixColumn, ...originColumns, ...rentPeriodColumn, ...suffixColumn])
  }, [prefixColumn, rentPeriodColumn, suffixColumn])

  const asyncData = (data, type) => {
    // console.log(type, data)
    const list = data.map(i => {
      const { type, buyout_price, rent_plan_id, formatId } = i
      if (Package && Package.length) {
        if (type === 'buy') {
          const planItem = Package.find(p => p.id === rent_plan_id)
          let deposit = 0
          let calFlag = false

          if (planItem) {
            const { first_pay_ratio, terms } = planItem
            if (first_pay_ratio && terms && buyout_price) {
              deposit = Number(((buyout_price / 100) * first_pay_ratio).toFixed(2))
              const perTerm = Number(((buyout_price - deposit) / terms).toFixed(2))
              calFlag = true
              planItem.rent_period.forEach(r => {
                const key = `period_id_${r.id}`
                i[key] = `¥ ${perTerm}`
                // FormRef.current.setFieldValue(`${formatId}-${key}`, perTerm);
                const perKey = key + '-perday'
                i[perKey] = ((buyout_price - deposit) / r.total_days).toFixed(2) + '元/天'
              })
            }
          }
          i.deposit = deposit ? `¥ ${deposit}` : '请输入购买价'
          if (!calFlag) {
            planItem.rent_period.forEach(r => {
              const key = `period_id_${r.id}`
              const perKey = key + '-perday'
              i[key] = '请输入购买价'
              i[perKey] = '请输入购买价'
            })
          }
        }
      }

      return i
    })
    skuListRef.current = list
    setSkuList(list)
    changeStore(list)
    onChange(list)
  }

  const changeStore = list => {
    // dataStore.current = []
    // return
    list.forEach(i => {
      const index = dataStore.current.findIndex(it => it.id === i.id)
      if (index > -1) {
        dataStore.current[index] = i
      } else {
        dataStore.current.push(i)
      }
    })
  }

  const getStorageData = tempSku => {
    // console.log('dataStore.current', dataStore.current)
    // console.log('getStorageData', FormRef.current.getFieldsValue(), tempSku[0].id, tempSku[0].formatId)
    // return []
    return tempSku.map(item => {
      const { formatId } = item
      const fieldsValue = FormRef.current.getFieldsValue()
      const key = formatId + '-'
      const res = {}

      Object.keys(fieldsValue).forEach(i => {
        if (i.includes(key)) {
          res[i.replace(key, '')] = fieldsValue[i]
        }
      })
      return { ...res, id: formatId }
    })
  }

  const sumData = skuFormatedList => {
    const storageData = getStorageData(skuFormatedList)
    if (skuFormatedList.length && dataStore.current.length) {
      const res = skuFormatedList.map(item => {
        const skuData =
          dataStore.current.find(i => {
            if (i.id === item.id || i.formatId === item.formatId) {
              return true
            } else {
              const formtStr = sourceMap
                .map(t => item[t])
                .filter(t => t)
                .join('-')
              const storeStr = sourceMap
                .map(t => i[t])
                .filter(t => t)
                .join('-')
              return formtStr === storeStr
            }
          }) || {}

        const stoData = storageData.find(i => i.id === item.id) || {}
        // console.log('dataItem', skuData, stoData)
        return {
          ...item,
          ...skuData,
          first_sku_value: item.first_sku_value,
          id: skuData.id || item.formatId,
          show_flag: skuData.show_flag || skuData.show_flag === 0 ? skuData.show_flag : 1,
          ...stoData
        }
      })
      asyncData(res, 'sumData res')
    } else {
      asyncData(
        skuFormatedList.map(i => ({
          ...i,
          id: i.id || i.formatId
        })),
        'sumData skuFormatedList'
      )
    }
  }

  useEffect(() => {
    const list = value ? [...value] : []
    if (value && value.length && periodListRef.current && periodListRef.current.length) {
      list.forEach(skuData => {
        Object.keys(skuData).forEach(keyName => {
          if (keyName.includes('period_id_')) {
            const id = Number(keyName.replace('period_id_', ''))
            const totalDays = periodListRef.current.find(i => i.id === id).total_days
            const dataIndex = keyName + '-perday'
            const value = skuData[keyName]
            // console.log('value', value)
            if (value) {
              skuData[dataIndex] = (value / totalDays).toFixed(2) + '元/天'
            } else {
              // console.log('缺少价格参数', skuData[dataIndex])
              skuData[dataIndex] = '缺少价格参数'
            }
          }
        })
      })
    }
    asyncData(list, 'value')
  }, [])

  const handleChangeIsHide = (e, index) => {
    const newList = [...skuListRef.current]
    newList[index].show_flag = e ? 1 : 0

    asyncData(newList)
    onChange(newList)
  }

  const formatSkuList = () => {
    let newList = []
    let newColumns = []
    if (Package && Package.length) {
      const tempSpuList = Spu
        ? Spu.map(i => ({
            ...i,
            values: i.values.filter(it => it.sku_value)
          }))
        : []
      const spuList = tempSpuList.filter(i => i.name && i.values.length)
      let tempList = []
      if (spuList.length) {
        spuList.forEach((spu, index) => {
          const restSpuList = spuList.slice(index + 1)
          //columns format
          if (restSpuList.length) {
            const restLength = restSpuList.reduce((pv, nv) => pv * nv.values.length, 1)
            newColumns.push({
              title: spu.name,
              dataIndex: skuNameList[index],
              onCell: (_, idx) => {
                return {
                  rowSpan: idx % restLength === 0 ? restLength : 0
                }
              }
            })
          } else {
            newColumns.push({
              title: spu.name,
              dataIndex: skuNameList[index]
            })
          }

          tempList = spuList.reduce((list, currentSup, currentIndex) => {
            let processingList = []
            if (list.length) {
              list.forEach(litem => {
                currentSup.values.forEach((curSku, curIdx) => {
                  processingList.push({
                    ...litem,
                    [skuNameList[currentIndex]]: curSku.sku_value,
                    skuName: `${litem.skuName}-${curSku.sku_value}`,
                    formatId: `${litem.formatId}-${curSku.id}`
                  })
                })
              })
            } else {
              currentSup.values.forEach((curSku, curIdx) => {
                processingList.push({
                  [skuNameList[currentIndex]]: curSku.sku_value,
                  skuName: curSku.sku_value,
                  formatId: curSku.id
                })
              })
            }
            return processingList
          }, [])
        })
      }

      if (tempList.length) {
        newColumns.unshift({
          title: '套餐',
          dataIndex: 'package_name',
          onCell: (_, index) => {
            return {
              rowSpan: index % tempList.length === 0 ? tempList.length : 0
            }
          }
        })
        Package.forEach(rentItem => {
          tempList.forEach(spu => {
            const formatId = `${rentItem.id}-${spu.formatId}`
            newList.push({
              ...spu,
              package_name: rentItem.package_name,
              rent_plan_id: rentItem.id,
              type: rentItem.type,
              formatId: formatId,
              show_flag: 1
              // id: spu.id || formatId
            })
          })
        })
      }
      const rentPeriodList = Package.filter(i => i.rent_period && i.rent_period.length)
      if (rentPeriodList.length) {
        const periodList = rentPeriodList.reduce((total, curPer) => {
          let temp = curPer.rent_period.reduce((subTotal, subCurPer) => {
            if (total.find(i => i.id === subCurPer.id && i.total_days === subCurPer.total_days)) {
              return subTotal
            } else {
              return [...subTotal, subCurPer]
            }
          }, [])
          return [...total, ...temp]
        }, [])

        periodListRef.current = periodList

        setRentPeriodColumn(
          periodList.map(per => ({
            title: per.rent_period,
            dataIndex: `period_id_${per.id}`,
            editable: true,
            type: 'number'
          }))
        )
      }
    }
    setPrefixColumn(newColumns)
    sumData(newList)
  }

  const handleChangeShowPer = e => {
    setShowPer(e.target.checked)
    if (e.target.checked) {
      setSuffixColumn(
        periodListRef.current.map(per => ({
          title: `${per.rent_period}/日租金`,
          dataIndex: `period_id_${per.id}-perday`
        }))
      )
    } else {
      setSuffixColumn([])
    }
  }

  const onDataChange = (value, index, key, record) => {
    const newData = [...skuListRef.current]
    newData[index][key] = value
    const needCal = key.includes('period_id_')
    if (needCal) {
      const id = Number(key.replace('period_id_', ''))
      const dataItem = periodListRef.current.find(i => i.id === id)
      const totalDays = dataItem.total_days
      const dataIndex = key + '-perday'
      if (value) {
        newData[index][dataIndex] = (value / totalDays).toFixed(2) + '元/天'
      } else {
        newData[index][dataIndex] = '缺少价格参数'
      }
    }
    // console.log('onDataChange', value, newData)
    asyncData(newData)
    onChange(newData)
  }

  // console.log('skuList', skuList)
  return (
    <Card
      title={
        <>
          <Checkbox checked={showPer} onChange={handleChangeShowPer}>
            预览日租金
          </Checkbox>
        </>
      }
      className={styles.sku_card_wrapper}
    >
      <SkuTable dataSource={skuList} originColumns={tableColumn} onDataChange={onDataChange}></SkuTable>
    </Card>
  )
}

export default () => {
  return (
    <Form.Item name='sku' label='规格明细'>
      <SkuTableWrapper></SkuTableWrapper>
    </Form.Item>
  )
}
